package com.weishenai.customerassistant.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MyExcelUtil {
    private Configuration configuration = null;
    @Value("${file.materialsExcel}")
    private String excelBaseUrl;
    @Value("${file.materialsExcelOut}")
    private String outBaseUrl;

    public MyExcelUtil() {
        configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
    }

    /**
     * 该方法单机情况下没问题，集群方案需要采用分布式锁，保证数据不会出错
     *
     * @param name
     * @param substation
     * @param fileName
     * @return
     */
    public synchronized File createExcel(String name, String substation, String fileName, String ourUrl) {
        String fileUrl = ourUrl + substation + name + fileName + ".xls";
        File dirFile = new File(ourUrl);
        if (!dirFile.exists()) dirFile.mkdirs();
        log.info("ExcelFileURL:" + fileUrl);
        //构造参数
        Map<String, Object> dataMap = getData(name, substation);
        configuration.setClassForTemplateLoading(MyExcelUtil.class, "");//模板文件所在路径
        Template t = null;
        try {
            configuration.setDirectoryForTemplateLoading(new File(excelBaseUrl));
            t = configuration.getTemplate(fileName + ".ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
        File outFile = new File(fileUrl); //导出文件名字
        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        try {
            t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件
            return outFile;
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 封装数据
     *
     * @param name       检察员
     * @param substation 供电所
     * @return
     */
    private Map<String, Object> getData(String name, String substation) {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("name", name);
        dataMap.put("substation", substation);
        return dataMap;
    }
}
